package com.newsproject.service.impl;

import com.newsproject.service.MinioService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class MinioServiceImpl implements MinioService {
    @Autowired
    private MinioClient minioClient;

    @Value("${minio.endpoint-url}")
    private String endpoint;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Value("${minio.bucket-name2}")
    private String bucketName2;



    private static final List<String> ALLOWED_TYPES = Arrays.asList(
            "video/mp4", "video/quicktime", "video/x-msvideo"
    );


    @Override
    public String uploadVideo(MultipartFile file) throws Exception {
        String contentType = file.getContentType();
        if (!ALLOWED_TYPES.contains(contentType)) {
            throw new IllegalArgumentException("不支持的视频格式");
        }
        // 生成存储路径
        String objectName = generateObjectName(file.getOriginalFilename());
        // 上传到Minio
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(contentType)
                        .build()
        );
        // 返回访问URL（确保bucket可公开访问）
        log.info("http://47.110.147.12:19000/" + bucketName + "/" + objectName);
        return "http://47.110.147.12:19000/" + bucketName + "/" + objectName;
    }

    @Override
    public String uploadImage(String base64) throws Exception {
        // 分离Base64头部和实际数据
        base64 = base64.replaceAll("\\s", "");
        String[] parts = base64.split(",");
        if(parts.length<2){
            throw new IllegalArgumentException("无效的Base64字符串" );
        }
        String dataPrefix = parts[0];
        String data = parts[1];

        // 获取MIME类型
        String mimeType = dataPrefix.split(";")[0].split(":")[1];

        // 解码Base64
        byte[] bytes = Base64.getDecoder().decode(data);

        // 生成唯一文件名
        String objectName = UUID.randomUUID().toString().replace("-", "").substring(0, 8)
                + "." + mimeType.split("/")[1];

        // 上传到Minio
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket("picture")
                        .object(objectName)
                        .stream(new ByteArrayInputStream(bytes), bytes.length, -1)
                        .contentType(mimeType)
                        .build()
        );
        // 返回访问URL（确保bucket可公开访问或生成预签名URL）
        return String.format("%s/%s/%s", endpoint, "picture", objectName);
    }

    @Override
    public String uploadImage(MultipartFile file) throws Exception {

            log.info(file.getOriginalFilename());
            log.info(file.getContentType());
            log.info(String.valueOf(file.isEmpty()));
            String contentType = file.getContentType();
            log.info(contentType);
            if(!contentType.contains("image/")){
                throw new IllegalArgumentException("不支持的图片格式");
            }
            String objectName = generateObjectName(file.getOriginalFilename());
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName2)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(contentType)
                    .build()
            );
            log.info("http://47.110.147.12:19000/" + bucketName2 + "/" + objectName);
            return "http://47.110.147.12:19000/" + bucketName2 + "/" + objectName;
    }


    private String generateObjectName(String originalName) {
        return  UUID.randomUUID() + "_" + originalName;
    }


}





